package com.xjtu.controller;



import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xjtu.common.constant.Role;
import com.xjtu.config.SocketManager;
import com.xjtu.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Arrays;


@ServerEndpoint("/call/{role}/{id}/{deviceId}")
@Controller
@Slf4j
public class WebSocketController {

    private User user;

    @OnOpen
    public void onOpen(Session session,
                       @PathParam("role") String role,
                       @PathParam("id") String id,
                       @PathParam("deviceId") String deviceId) {
        user = new User();
        if (Arrays.asList(Role.ROLES).contains(role)) user.setRole(role);
        else user.setRole("others");
        user.setDeviceId(deviceId);
        user.setId(id);
        //添加在线信息
        SocketManager.addSession(deviceId, session);
        SocketManager.addUser(deviceId, user);
    }

    @OnClose
    public void onClose(Session session) {
        SocketManager.removeSession(session.getId());
        SocketManager.removeUser(user.getDeviceId());
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        String id = SocketManager.findIdBySessionId(session.getId());
        log.error("设备ID为{}的连接出错", id);
        throwable.printStackTrace();
        SocketManager.removeSession(session.getId());
        SocketManager.removeUser(user.getDeviceId());
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        //消息体
        JSONObject data = JSON.parseObject(message);
        String type = data.getString("type");  //消息类型
        //心跳
        if ("pong".equals(type)) {
            log.error("设备ID为{}的连接发来pong", SocketManager.findIdBySessionId(session.getId()));
            return;
        }
        //处理消息体
        JSONObject body = data.getJSONObject("message");
        String from = body.getString("userId");  //源设备id
        String to = body.getString("toUserId");  //目的设备id
        if (type.equals("hungUp")) return;
        //消息转发
        SocketManager.sendMessage(to, message);
    }
}
